<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\controller\Util;
use fast\Form;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 课程
 *
 * @icon fa fa-circle-o
 */
class Course extends Backend
{
    
    /**
     * Course模型对象
     * @var \app\admin\model\Course
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Course;
        $this->view->assign("typeStatusList", $this->model->getTypeStatusList());
        $this->view->assign("isFreeList", $this->model->getIsFreeList());
        $this->view->assign("isPromotionList", $this->model->getIsPromotionList());
        $this->view->assign("isDiscountList", $this->model->getIsDiscountList());
        $this->view->assign("isIssueList", $this->model->getIsIssueList());
        $this->view->assign("isCheckList", $this->model->getIsCheckList());
        $this->view->assign("isApplyList", $this->model->getIsApplyList());
        $this->view->assign("difficultyList", $this->model->getDifficultyList());
        $group = Db::name('auth_group_access')->where('uid', $this->auth->id)->find()['group_id'];
        $this->view->assign("group",$group);
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $wheres = [];
            if($this->auth->id != 1){
                $teacherInfo = Util::getUserInfo($this->auth->id,'admin_id');
                $wheres['course.teacher_id'] = $teacherInfo['id'];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['teacher','helper','classify','tag'])
                    ->where($where)->where($wheres)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['teacher','helper','classify','tag'])
                    ->where($where)->where($wheres)
                    ->order('type_status ASC')
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                
            }
            $list = collection($list)->toArray();
            foreach ($list as $k => &$v){
                $data = Db::query("select tag_name from `by_tag` where FIND_IN_SET(id,'" . $v['tag_ids'] ."')" );
                $data = array_column($data,'tag_name');
                if(is_array($data)){
                    $v['tag']['tag_name'] = implode("/",$data);
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['create_time'] = date("Y-m-d H:i:s");
                    $params['content']    .= "<style type='text/css'>img {width: 100%;display:block;}</style>";
                    $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
                    $replacement = $this->request->root(true) .'${1}';
                    $params['content'] =  preg_replace($pattern, $replacement,$params['content']);
                    if($this->auth->id){
                        $teacher = \app\admin\model\Teacher::get(['admin_id'=>$this->auth->id]);
                        if($teacher){
                            $params['teacher_id'] = $teacher['id'];
                        }
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $teacher_id = Db::name('teacher')->where('admin_id',$this->auth->id)->find()['id'];
        $this->assign('teacher_id',$teacher_id);
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function selectpage()
    {
        return parent::selectpage(); // TODO: Change the autogenerated stub
    }

    // 教师提交审核
    public function putCheck($ids = ""){
        if(!empty($ids)){
           $res =  Db::name('course')->where('id',$ids)->update(['is_check'=>1]);
           if($res){
                $this->success("该课程成功提交审核,期间不可进行修改操作");
           }
        }
         $this->error("提交失败");
    }
    // admin审核课程
    public function check($ids =""){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch('check');
    }
    public function teacherIssue(){
        $param = input();
        $res = Db::name('course')->where('id',$param['ids'])->update(['is_issue' => $param['is_issue']]);
        empty($res) ? $this->error() : $this->success($param['is_issue'] == 1 ? '发布成功' : "取消成功");
    }

}
